/**
 * @a https://leetcode.cn/problems/3sum/
 */

#include "common.h"


class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int sz = nums.size();
        vector<vector<int>> ret;
        for(int i = 0; i < sz - 2; ++i)
        {
            if(nums[i] > 0) return ret;
            while(i >= 1 && i < sz - 2 && nums[i] == nums[i - 1]) ++i;

            int left = i + 1, right = sz - 1;
            while(left < right){
                if(nums[i] + nums[left] + nums[right] == 0)
                {
                    ret.push_back({nums[i],nums[left],nums[right]});
                    while(left + 1 < right && nums[left] == nums[left + 1]) left++;
                    while(right - 1 > left && nums[right] == nums[right - 1]) right--;
                    left++;
                    right--;
                }
                else if(nums[i] + nums[left] + nums[right] > 0) right--;
                else left++;
            }
        }
        return ret;
    }
};